package com.dchh.android.suverynew.act;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.AddListAdapter;
import com.dchh.android.suverynew.adapter.SlideAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.views.RadioPageView;
import com.dchh.android.suverynew.views.SelectPoupWindow;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.BasicProperties;
import com.dhcc.android.base.common.bean.Config;
import com.dhcc.android.base.common.bean.File;
import com.dhcc.android.base.common.bean.Item;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.MyActorPopWindow;
import com.dhcc.android.base.db.DBImportUtil;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.db.Sqlite.DKSearchDBManager;
import com.dhcc.android.base.db.Sqlite.RecordDBManager;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.DKMapUtil;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.FormUtil;
import com.dhcc.android.base.utils.MixUIUtil;
import com.dhcc.android.base.utils.StringUtil;
import com.dhcc.android.base.utils.dataparse.ConfigParse;
import com.dhcc.android.base.utils.dataparse.ThcParse;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调查填报
 *
 * @author zhoudan
 * @date 2016年1月4日
 */
public class MyDemandActivity extends SBaseActivity implements MixUIUtil.MixUIListener {

    private RelativeLayout main;
    private LinearLayout view;
    private LinearLayout back;

    /**
     * 调查对象页面集合
     */
    public List<File> fileList = new ArrayList<File>();
    /**
     * View集合
     */
    private List<View> mViews = new ArrayList<View>();
    /**
     * 页面名称集合
     */
    private List<String> radioButtonStrList = new ArrayList<String>();
    /**
     * 任务包存储路径
     */
    private String root;
    /**
     * 任务包路径
     */
    public String pkgPath;
    /**
     * transport路径
     */
    public String transPath;
    /**
     * 配置文件路径
     */
    public String xmlPath;
    /**
     * 数据库路径
     */
    public String dbPath;
    /**
     * 数据库管理工具
     */
    public static DBManagerUtil dBManagerUtil;
    // 相关重要参数
    private String taskName;
    private String periodCode;
    private String periodLabel;

    private String DKID;
    private String YFBHU;
    private ImageView zrdkImageView;
    /**
     * 地块工具类
     */
    DKMapUtil dkMapUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setToolBarShow(false);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_demand_main);
    }

    @Override
    protected void setTitle(TextView toolbar_title) {
        toolbar_title.setText(Constants.getTempData(this, MSApplication.TASK));
    }

    /**
     * 页面初始化准备
     */
    public void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        // 需要传递过来的参数
        YFBHU = getIntent().getStringExtra("YFBHU");
        periodCode = Constants.getTempData(this, MSApplication.PERIOD_CODE);
        periodLabel = Constants.getTempData(this, MSApplication.PERIOD_LABEL);
        pkgPath = root + "/" + taskName;
        transPath = pkgPath + "/TASK/TRANSPORT/";
        xmlPath = pkgPath + "/DEMAND/";
        dbPath = transPath + "DATA.db";
        dBManagerUtil = DBManagerUtil.getInstance(transPath, this);
        dkMapUtil = new DKMapUtil(this);
        Config config = null;
        ConfigParse pull = new ConfigParse();
        InputStream input = null;
        try {
            input = new FileInputStream(xmlPath + "C_TRANSPORT.xml");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //将早稻面积 作为 春播面积的 另一个入口
        String per = periodCode.equals("007") ? "003" : periodCode;
        config = (Config) pull.getXmlObject(input, per);
        //
        DKID = Constants.select.get(config.getFeild());

        if (config != null) {
            fileList.clear();
            fileList = config.getFile();
            // 循环遍历标签页
            if (fileList != null && fileList.size() > 0) {
                for (int i = 0; i < fileList.size(); i++) {
                    File file = fileList.get(i);
                    if (file.getName().equals("基本信息")) {// 如果是‘基本信息’
                        initBaseInfo(file);
                    } else {
                        radioButtonStrList.add(file.getName());
                        View carrierView = getLayoutInflater().inflate(R.layout.my_pager_carrier_main, null);
                        LinearLayout carrier_layout = (LinearLayout) carrierView.findViewById(R.id.carrier_layout);

                        // 渲染
                        // 含有增加表单
                        BasicProperties add = file.getAdd();
                        if (add != null && StringUtil.isNotEmpty(add.getTitle())) {//
                            initAddData(add, carrierView, carrier_layout, file);
                        }

                        // 含有子列表
                        List<Item> itemList = file.getItem();// 子页面项
                        if (itemList != null && itemList.size() > 1) {
                            View childView = initListView(carrier_layout);

                            initListData(file, childView);
                        }

                        // 混合
                        BasicProperties mix = file.getMix();
                        if (mix != null && StringUtil.isNotEmpty(mix.getTitle())) {
                            initMixView(file, carrierView, carrier_layout);
                        }

                        mViews.add(carrierView);
                    }
                }

                RadioPageView pageView = new RadioPageView(view, this, null, false);
                pageView.iniController(mViews, radioButtonStrList);
                if (radioButtonStrList != null && radioButtonStrList.size() > 0) {
                    pageView.setChecked(Constants.radioPageViewFlag);
                }
            }
        }
        back = (LinearLayout) main.findViewById(R.id.back_btn);
        back.setOnClickListener(backListener);
        StringUtil.dismissDialog(Constants.DIALOG);
        Constants.DIALOG = null;
        f3 = getIntent().getBooleanExtra("f3", true);

    }

    // ----------------相关组件渲染处理---------------------------

    private String tablename1, tablename2;
    private List<BasicProperties> fieldList1, fieldList2;
    private List<String> keys1, keys2;

    private List<Map<String, String>> getZWLIST(String feild) {
        //// 作物
        tablename1 = "作物" + CommenUtil.getDCQ(periodLabel);
        String property1 = "作物" + CommenUtil.getDCQ(periodLabel) + ".thc";
        String zwbh1 = "ZWBH", mjkey1 = "ZWMJ";
        ;

        InputStream inputStream1 = CommenUtil.initStreamData(property1, xmlPath, this);
        fieldList1 = ThcParse.getXmlThc(inputStream1);
        keys1 = CommenUtil.basicPropertieToStrList(fieldList1, zwbh1); // 字段集合

        List<Map<String, String>> zwlist = dBManagerUtil.getMixListData(tablename1, keys1, feild, DKID, null,
                dbPath + "DATA.db", mjkey1);

        return zwlist;
    }

    private List<Map<String, String>> getSSLIST(String feild) {
        //// 设施
        tablename2 = "设施" + CommenUtil.getDCQ(periodLabel);
        String property2 = "设施.thc";
        String mjkey2 = "SNZWMJ", zwbh2 = "SNZWBH";

        InputStream inputStream2 = CommenUtil.initStreamData(property2, xmlPath, this);
        fieldList2 = ThcParse.getXmlThc(inputStream2);
        keys2 = CommenUtil.basicPropertieToStrList(fieldList2, zwbh2); // 字段集合

        List<Map<String, String>> sslist = dBManagerUtil.getMixListData(tablename2, keys2, feild, DKID, null,
                dbPath + "DATA.db", mjkey2);

        return sslist;
    }

    // ++++++++++++++++++++++++混合+++++++++++++++++++++++++++++++
    /**
     * 数据集合
     */
    private List<Map<String, String>> olddatas = new ArrayList<Map<String, String>>();
    private LinearLayout nodata;
    private static final String SSNYYDLX = "设施农业用地类型";
    /*private static final String NZW = "农作物";
    private static final String YYGS = "园艺果树";
	private static final String LM = "林木";
	private static final String CD = "草地";
	private static final String SY = "水域";
	private static final String JZW = "建筑物";
	private static final String DL = "道路";
	private static final String QTYD = "其他用地";*/
    /**
     * 图斑类型--值
     */
    private KeyValueBean oldTBLX;
    /**
     * 保存的图斑类型 1-作物 ，2-设施
     */
    private int saveTBLX = 1;
    /**
     * 混合标签页 --页面载体
     */
    private LinearLayout mixcontent;
    /**
     * 图斑类型数据集合
     */
    private List<KeyValueBean> tblxList = new ArrayList<KeyValueBean>();
    /**
     * 面积对应的字段名
     */
    public String mjkey;

    /**
     * 初始化混合页面
     */
    private void initMixView(final File file, final View carrierView, final LinearLayout carrier_layout) {
        // 渲染
        RelativeLayout mixlayout = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.util_mix, null);
        carrier_layout.addView(mixlayout);

        LinearLayout mixtopsel = (LinearLayout) mixlayout.findViewById(R.id.mix_top_sel);
        final TextView tblx = (TextView) mixlayout.findViewById(R.id.tblx_text);
        mixcontent = (LinearLayout) mixlayout.findViewById(R.id.mix_content);

        // 获取作物表和设施表的数据
        List<Map<String, String>> zwlist = getZWLIST(file.getFeild());
        List<Map<String, String>> sslist = getSSLIST(file.getFeild());

        // 获取所有图斑类型
        if (tblxList.size() == 0) {
            tblxList = getTblxList();
        }

        List<BasicProperties> fieldList = null;
        // 设置默认图斑类型
        if (Constants.isListEmpty(zwlist)) {// 判断作物列表是否为空
            if (Constants.isListEmpty(sslist)) {// 判断设施列表是否为空
                olddatas.clear();
                oldTBLX = new KeyValueBean("100", "农作物");
                saveTBLX = 1;
                fieldList = fieldList1;
            } else {
                olddatas = Constants.setListToList(sslist, olddatas);
                oldTBLX = new KeyValueBean("900", SSNYYDLX);
                saveTBLX = 2;
                fieldList = fieldList2;
            }
        } else {
            olddatas = Constants.setListToList(zwlist, olddatas);
            oldTBLX = getTBLXFromList(zwlist, "ZWLX");
            saveTBLX = 1;
            fieldList = fieldList1;
        }
        tblx.setText(oldTBLX.getValue());

        // 默认设置作物填充页面
        fillMixcontent(file, oldTBLX.getValue(), fieldList, carrierView, mixcontent);

        // 图斑类型选择点击监听
        mixtopsel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (tblxList.size() == 0) {
                    tblxList = getTblxList();
                }

                SelectPoupWindow selpw = new SelectPoupWindow(MyDemandActivity.this);
                selpw.show(v, new SelectPoupWindow.OnSelectListener() {

                    @Override
                    public void onSelectString(View view, final String value) {
                    }

                    @Override
                    public void onSelectKeyValueBean(View view, final KeyValueBean kv) {
                        // 图斑类型改变
                        if (!kv.getValue().equals(oldTBLX.getValue())) {
                            String nv = kv.getValue();
                            String ov = oldTBLX.getValue();

                            oldTBLX = kv;
                            tblx.setText(kv.getValue());

                            kvlist.clear();
                            if (ov.equals(SSNYYDLX)) {// 设施 --》作物
                                olddatas.clear();
                                List<Map<String, String>> zwlist = getZWLIST(file.getFeild());
                                olddatas = Constants.setListToList(zwlist, olddatas);

                                fillMixcontent(file, kv.getValue(), fieldList1, carrierView, mixcontent);
                                carrierView.postInvalidate();// 刷新父体
                                /*saveTBLX = 1;*/
                            } else if (nv.equals(SSNYYDLX)) {// 作物 --》设施
                                olddatas.clear();
                                List<Map<String, String>> sslist = getSSLIST(file.getFeild());
                                olddatas = Constants.setListToList(sslist, olddatas);

                                fillMixcontent(file, kv.getValue(), fieldList2, carrierView, mixcontent);
                                carrierView.postInvalidate();// 刷新父体
                                /*saveTBLX = 2;*/
                            } else {// 作物 --》 作物

                                if (!SPreferencesManager.getValue(MSApplication.DK_TZ, false)) {
                                    // 套种关闭 编辑：郭天雨
                                    String filter = "CLASSIFICATION='" + kv.getValue() + "（" + kv.getKey() + "）'";
                                    kvlist = dBManagerUtil.getZWDatas("DIC_ZW",
                                            new KeyValueBean("PID", "VALUE", "CLASSIFICATION"), filter,
                                            xmlPath + "DEMAND.db");
                                } else {
                                    // 套种开启 编辑：郭天雨
                                    kvlist = dBManagerUtil.getZWDatas("DIC_ZW",
                                            new KeyValueBean("PID", "VALUE", "CLASSIFICATION"), null,
                                            xmlPath + "DEMAND.db");
                                }

                                tbkey = "ZWLX";
                                tbvalue = kv.getValue();
                            }

                        }
                    }

                }, null, tblxList);
            }
        });
    }

    /**
     * 原 单位 1--亩 2--平方米
     */
    public int oldUnit = 1;
    /**
     * 面积对应的输入框
     */
    private EditText mj_input;

    /**
     * 填充公共部分
     */
    private void fillMixcontent(File file, String type, List<BasicProperties> fieldList, View carrierView,
                                LinearLayout mixcontent) {
        // 清空载体
        mixcontent.removeAllViews();
        oldUnit = 1;
        // 判断类型
        if (SSNYYDLX.equals(type)) {
            // 获取设施农业用地类型数据
            if (sslxList == null || sslxList.size() == 0) {
                String filter = "CLASSIFICATION='" + oldTBLX.getValue() + "（" + oldTBLX.getKey() + "）'";
                sslxList = getSSLXList(filter);
            }
            old_sslx = getSSLXFromList(olddatas, "SNYD");

            //处理没有作物的空设施数据
            if (olddatas.size() == 1) {
                String zwmc = olddatas.get(0).get("SNZWMC");
                if (StringUtil.isEmpty(zwmc)) {
                    olddatas.clear();
                }
            }

            LinearLayout ssview = (LinearLayout) getLayoutInflater().inflate(R.layout.util_sheshi_list, null);
            mixcontent.addView(ssview);
            initChildView(type, fieldList, file, carrierView, ssview);
        } else {
            LinearLayout addListView = (LinearLayout) getLayoutInflater().inflate(R.layout.util_add_list, null);
            mixcontent.addView(addListView);
            initChildView(type, fieldList, file, carrierView, addListView);
        }
    }

    public String tbkey;
    public String tbvalue;

    /**
     * 设施农业用地类型数据集合
     */
    private List<String> sslxList;
    /**
     * 设施农业用地类型-值
     */
    private String old_sslx;
    private LinearLayout listContent;

    /**
     * 初始化子页面
     */
    private void initChildView(String type, List<BasicProperties> fieldList, File file, final View carrierView,
                               LinearLayout addListView) {

        // 显示保存按钮
        LinearLayout save_layout = (LinearLayout) carrierView.findViewById(R.id.save_layout);
        save_layout.setVisibility(View.VISIBLE);

        // 获取组件
        TextView addTextview = (TextView) addListView.findViewById(R.id.add);
        listContent = (LinearLayout) addListView.findViewById(R.id.content);

        // 面积
        tb_all = (TextView) addListView.findViewById(R.id.sel_title);
        tb_all_label = (TextView) addListView.findViewById(R.id.tb_all_label);
        tb_ok_label = (TextView) addListView.findViewById(R.id.tb_ok_label);
        tb_ok = (TextView) addListView.findViewById(R.id.tb_ok);
        tb_no_label = (TextView) addListView.findViewById(R.id.tb_no_label);
        tb_no = (TextView) addListView.findViewById(R.id.tb_no);
        tb_over_label = (TextView) addListView.findViewById(R.id.tb_over_label);
        tb_over = (TextView) addListView.findViewById(R.id.tb_over);
        String zwfilter = "", zwbh = "";
        int adptype = 0;
        if (SSNYYDLX.equals(type)) {
            mjkey = "SNZWMJ";
            adptype = 2;
            zwbh = "SNZWBH";
            zwfilter = "CLASSIFICATION!='设施农业用地类型（900）'";

            tbkey = "SNYD";
            tbvalue = old_sslx;
        } else {
            if (!SPreferencesManager.getValue(MSApplication.DK_TZ, false)) {
                // 套种关闭 编辑：郭天雨
                mjkey = "ZWMJ";
                adptype = 1;
                zwbh = "ZWBH";
                zwfilter = "CLASSIFICATION='" + oldTBLX.getValue() + "（" + oldTBLX.getKey() + "）'";
                tbkey = "ZWLX";
                tbvalue = type;
            } else {
                // 套种开启 编辑：郭天雨
                mjkey = "ZWMJ";
                adptype = 1;
                zwbh = "ZWBH";
                zwfilter = "";
                tbkey = "ZWLX";
                tbvalue = type;
            }
        }
        final KeyValueBean kv = CommenUtil.getSelectListKey(fieldList);
        final List<KeyValueBean> jcfields = CommenUtil.getJCField(fieldList); // 需要继承的字段集合
        final String listKey = kv.getKey();
        // listview的操作监听
        MixUIUtil.OnMixListOperateListener oplistener = new MixUIUtil.OnMixListOperateListener() {
            /**
             * 删除选择
             */
            @Override
            public void OnCheckClick(int position, boolean isChecked) {
                Map<String, String> map = olddatas.get(position);
                map.put("checkFlag", isChecked ? "1" : "0");

                if (isChecked) {// 选中
                    results.add(map);
                } else {// 没有选中
                    for (Map<String, String> res : results) {
                        if (res.get(listKey).equals(map.get(listKey))) {
                            results.remove(res);
                            break;
                        }
                    }
                }

                if (results.size() > 0) {
                    del_num.setText("(" + results.size() + ")");
                } else {
                    del_num.setText("");
                }
            }

            /**
             * 几何计算按钮点击
             */
            @Override
            public void OnBtnClick(int position, Button btn, EditText mj_edit) {
                if (StringUtil.isFastDoubleClick(500)) {
                    return;
                }
                mj_input = mj_edit;
                File file = new File();
                String table = CommenUtil.getTableName("样方自然地块", periodLabel);
                file.setTable(table);
                file.setPfeild("YFBHU");
                dkMapUtil.calculateAcreage(file);
            }
        };
        final MixUIUtil mixUiUtil = new MixUIUtil(this, olddatas, kv.getKey(), adptype, this);
        mixUiUtil.setDelFlag(false);
        mixUiUtil.setOnMixListOperateListener(oplistener);
        mixUiUtil.setUnitFlag(oldUnit);
        mixUiUtil.initListView(listContent);

        // 设施农业用地类型选择
        LinearLayout sstopsel = null;
        if (SSNYYDLX.equals(type)) {
            sstopsel = (LinearLayout) addListView.findViewById(R.id.sheshi_top_sel);
            final TextView sslx = (TextView) addListView.findViewById(R.id.sslx_text);
            sslx.setText(old_sslx);

            sstopsel.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (sslxList == null || sslxList.size() == 0) {
                        String filter = "CLASSIFICATION='" + oldTBLX.getValue() + "（" + oldTBLX.getKey() + "）'";
                        sslxList = getSSLXList(filter);
                    }

                    SelectPoupWindow spw = new SelectPoupWindow(MyDemandActivity.this);
                    spw.show(v, new SelectPoupWindow.OnSelectListener() {
                        @Override
                        public void onSelectString(View view, String value) {
                            if (!value.equals(old_sslx)) {
                                oldUnit = 1;
                                old_sslx = value;
                                sslx.setText(value);

                                tbkey = "SNYD";
                                tbvalue = old_sslx;
                            }
                        }

                        @Override
                        public void onSelectKeyValueBean(View view, KeyValueBean kv) {
                        }
                    }, sslxList);
                }
            });
        }

        // 处理 添加、删除、保存
        /**
         * 添加选择监听
         */
        MyActorPopWindow.OnSelectListener listener = new MyActorPopWindow.OnSelectListener() {

            @Override
            public void onSelect(List<Map<String, String>> results) {

            }

            @Override
            public void OnSingleSelect(Map<String, String> map) {
                Constants.showDialog(MyDemandActivity.this, "正在加载...");
                if (singleSelect(kv.getKey(), map)) {
                    mixUiUtil.refresh(listContent, olddatas);
                    selectSave = true;

                    refreshTBMJ(mjkey);
                }

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        Constants.closeDialog();
                    }
                }, 500);
            }
        };
        initADD(addTextview, zwfilter, zwbh, kv, listener);

        initDELETE(type, addListView, carrierView, mixUiUtil);

        // 切换
        TextView change = (TextView) addListView.findViewById(R.id.change);
        change.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (oldUnit == 1) {
                    mixUiUtil.setUnitFlag(2);
                    oldUnit = 2;
                } else {
                    mixUiUtil.setUnitFlag(1);
                    oldUnit = 1;
                }
                mixUiUtil.refresh(listContent, olddatas);
                refreshTBMJ(mjkey);
            }
        });
        final KeyValueBean pkv = new KeyValueBean(file.getFeild(), file.getPfeild());
        save_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (olddatas.size() > 0) {//数据不为空
                    // 判断填报面是否超出
                    if (tb_over.getVisibility() == View.GONE ||
                            //sp.getBoolean(MSApplication.DK_TZ,false)//广西版本、浙江
                            /*oldTBLX.getKey().equalsIgnoreCase("900")*/
                            getZWLX()) { // 一级分类内部各地物面积没有超出
                        if (SSNYYDLX.equals(oldTBLX.getValue())) {//是设施
                            if (saveTBLX == 1) {//之前保存的数据表是作物表，要清空作物数据
                                dBManagerUtil.deleteByFilter(tablename1, " DKBHU='" + DKID + "'", dbPath);
                            }
                            boolean flag = dBManagerUtil.add(YFBHU, olddatas, keys2, tablename2, pkv, jcfields,
                                    Constants.select, dbPath);
                            CommenUtil.toast("保存成功！", MyDemandActivity.this);
                            selectSave = false;
                            saveTBLX = 2;

                        } else {//是作物
                            if (saveTBLX == 2) {//之前保存的数据表是设施表，要清空设施数据
                                dBManagerUtil.deleteByFilter(tablename2, " DKBHU='" + DKID + "'", dbPath);
                            }
                            boolean flag = dBManagerUtil.add(YFBHU, olddatas, keys1, tablename1, pkv, jcfields,
                                    Constants.select, dbPath);
                            CommenUtil.toast("保存成功！", MyDemandActivity.this);
                            selectSave = false;
                            saveTBLX = 1;
                        }
                        // 保存已编辑
                        if (f1) {
                            f1 = false;
                            changeComplete("f1", "1");
                        }

                        //保存进度记录
                        RecordDBManager rcdDB = new RecordDBManager(MyDemandActivity.this);
                        rcdDB.add(DKID, YFBHU, "4", "003");

                        //保存图斑类型修订
                        dBManagerUtil.updateTBLXXD("样方自然地块" + CommenUtil.getDCQ(periodLabel), dbPath,
                                DKID, oldTBLX.getValue() + "(" + oldTBLX.getKey() + ")");

                    } else {// 面积超出
                        CommenUtil.toast("某图斑类型填报面积超出，无法保存！", MyDemandActivity.this);
                    }
                } else {//数据为空
                    //设施农业用地类型 且不是种植业设施用地  可以没有作物数据保存
                    if (SSNYYDLX.equals(oldTBLX.getValue()) && !old_sslx.equals("种植业设施用地")) {
                        if (saveTBLX == 1) {//之前保存的数据表是作物表，要清空作物数据
                            dBManagerUtil.deleteByFilter(tablename1, " DKBHU='" + DKID + "'", dbPath);
                        }
                        dBManagerUtil.add(YFBHU, DKID, old_sslx, CommenUtil.formatterMJ(mj_total), tablename2, dbPath);

                        CommenUtil.toast("保存成功！", MyDemandActivity.this);
                        selectSave = false;
                        saveTBLX = 2;

                        // 保存已编辑
                        if (f1) {
                            f1 = false;
                            changeComplete("f1", "1");
                        }
                        //保存进度记录
                        RecordDBManager rcdDB = new RecordDBManager(MyDemandActivity.this);
                        rcdDB.add(DKID, YFBHU, "4", "003");

                        //保存图斑类型修订
                        dBManagerUtil.updateTBLXXD("样方自然地块" + CommenUtil.getDCQ(periodLabel), dbPath,
                                DKID, oldTBLX.getValue() + "(" + oldTBLX.getKey() + ")");

                    } else {
                        //如果是删除了全部数据之后点击保存
                        if (isDeleteAll) {
                            isDeleteAll = false;
                            if (SSNYYDLX.equals(oldTBLX.getValue())) {//是设施
                                if (saveTBLX == 1) {//之前保存的数据表是作物表，要清空作物数据
                                    dBManagerUtil.deleteByFilter(tablename1, " DKBHU='" + DKID + "'", dbPath);
                                }
                                dBManagerUtil.deleteByFilter(tablename2, " DKBHU='" + DKID + "'", dbPath);
                            } else {//是作物
                                if (saveTBLX == 2) {//之前保存的数据表是设施表，要清空设施数据
                                    dBManagerUtil.deleteByFilter(tablename2, " DKBHU='" + DKID + "'", dbPath);
                                }
                                dBManagerUtil.deleteByFilter(tablename1, " DKBHU='" + DKID + "'", dbPath);
                            }
                            CommenUtil.toast("保存成功！", MyDemandActivity.this);
                        } else {
                            CommenUtil.toast("没有数据需要保存！", MyDemandActivity.this);
                        }
                    }
                }
            }
        });

        // 处理面积
        refreshTBMJ(mjkey);
    }

    private boolean getZWLX() {
        boolean flag = true;
        String zwbh = null;
        String zwmj = null;
        double myZwmj0 = 0;
        double myZwmj1 = 0;
        double myZwmj2 = 0;
        double myZwmj3 = 0;
        double myZwmj4 = 0;
        double myZwmj5 = 0;
        double myZwmj6 = 0;
        double myZwmj7 = 0;
        double myZwmj8 = 0;
        String zw0 = "0";
        String zw1 = "1";
        String zw2 = "2";
        String zw3 = "3";
        String zw4 = "4";
        String zw5 = "5";
        String zw6 = "6";
        String zw7 = "7";
        String zw8 = "8";
        for (Map<String, String> m : olddatas) {
            zwbh = m.get("ZWBH").substring(0, 1);
            if (zwbh.equals(zw0)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj0 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw1)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj1 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw2)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj2 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw3)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj3 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw4)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj4 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw5)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj5 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw6)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj6 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw7)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj7 += Double.parseDouble(zwmj.trim());
                }
            }
            if (zwbh.equals(zw8)) {
                if (m.get("ZWMJ") != null) {
                    zwmj = m.get("ZWMJ");
                    myZwmj8 += Double.parseDouble(zwmj.trim());
                }
            }
            if (myZwmj0 > mj_total || myZwmj1 > mj_total || myZwmj2 > mj_total || myZwmj3 > mj_total || myZwmj4 > mj_total
                    || myZwmj5 > mj_total || myZwmj6 > mj_total || myZwmj7 > mj_total
                    || myZwmj8 > mj_total) {
                flag = false;
            } else {
                flag = true;
            }
        }

        return flag;
    }

    /**
     * 删除选中的数量
     */
    private TextView del_num;
    /**
     * 删除选中结果集合
     */
    private List<Map<String, String>> results = new ArrayList<Map<String, String>>();
    /**
     * 是否删除了全部数据
     */
    private boolean isDeleteAll = false;

    /**
     * 初始删除操作
     */
    private void initDELETE(final String type, final LinearLayout content, final View carrierView,
                            final MixUIUtil mixUiUtil) {
        TextView delTextview = (TextView) content.findViewById(R.id.delete);

        RelativeLayout mixLayout = (RelativeLayout) carrierView.findViewById(R.id.mix_page_layout);
        final LinearLayout mixtopsel = (LinearLayout) mixLayout.findViewById(R.id.mix_top_sel);

        final LinearLayout delbtn = (LinearLayout) mixLayout.findViewById(R.id.del_layout);
        del_num = (TextView) mixLayout.findViewById(R.id.del_num);
        final RelativeLayout deltop = (RelativeLayout) mixLayout.findViewById(R.id.del_top_layout);
        TextView opcancle = (TextView) mixLayout.findViewById(R.id.op_cancle);

        // 显示删除操作界面
        delTextview.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (olddatas.size() > 0) {
                    mixUiUtil.setDelFlag(true);
                    mixUiUtil.refresh(listContent, olddatas);

                    if (SSNYYDLX.equals(type)) {
                        content.findViewById(R.id.sheshi_sel_content).setVisibility(View.GONE);
                        content.findViewById(R.id.sel_title_layout).setVisibility(View.GONE);
                    } else {
                        content.findViewById(R.id.sel_title_layout).setVisibility(View.GONE);
                    }
                    mixtopsel.setVisibility(View.GONE);
                    carrierView.findViewById(R.id.save_layout).setVisibility(View.GONE);

                    delbtn.setVisibility(View.VISIBLE);
                    deltop.setVisibility(View.VISIBLE);
                } else {
                    CommenUtil.toast("没有可以删除的数据", MyDemandActivity.this);
                }
            }
        });

        // 取消批量删除操作
        opcancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                closeDelete(type, delbtn, deltop, content, mixtopsel, carrierView);

                // 清空
                setDeleteCheck(false);
                results.clear();
                del_num.setText("");

                mixUiUtil.setDelFlag(false);
                mixUiUtil.refresh(listContent, olddatas);
            }
        });

        // 执行删除
        delbtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 删除
                if (results.size() > 0) {
                    final AlertDialog alertDialog = new AlertDialog(MyDemandActivity.this, "确定要删除所选记录？", "删除", "取消");
                    alertDialog.show();
                    alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {

                        @Override
                        public void doConfirm() {
                            alertDialog.dismiss();

                            //判断是否删除了全部数据
                            if (results.size() == olddatas.size()) {
                                isDeleteAll = true;
                            }

                            olddatas.removeAll(results);
                            CommenUtil.toast("删除成功", MyDemandActivity.this);

                            closeDelete(type, delbtn, deltop, content, mixtopsel, carrierView);

                            selectSave = true;

                            // 清空
                            setDeleteCheck(false);
                            results.clear();
                            del_num.setText("");

                            mixUiUtil.setDelFlag(false);
                            mixUiUtil.refresh(listContent, olddatas);

                            refreshTBMJ(mjkey);
                        }

                        @Override
                        public void doCancel() {
                            alertDialog.dismiss();
                        }
                    });

                } else {
                    CommenUtil.toast("没有可以删除的数据", MyDemandActivity.this);
                }
            }
        });
    }

    /**
     * 关闭删除操作界面
     */
    private void closeDelete(String type, LinearLayout delbtn, RelativeLayout deltop, LinearLayout content,
                             LinearLayout mixtopsel, View carrierView) {

        delbtn.setVisibility(View.GONE);
        deltop.setVisibility(View.GONE);

        if (SSNYYDLX.equals(type)) {
            content.findViewById(R.id.sheshi_sel_content).setVisibility(View.VISIBLE);
            content.findViewById(R.id.sel_title_layout).setVisibility(View.VISIBLE);
        } else {
            content.findViewById(R.id.sel_title_layout).setVisibility(View.VISIBLE);
        }

        // if(SSNYYDLX.equals(type)||NZW.equals(type)||YYGS.equals(type)||
        // LM.equals(type)||CD.equals(type)||SY.equals(type)||
        // JZW.equals(type)||DL.equals(type)||QTYD.equals(type)){
        // content.findViewById(R.id.sheshi_sel_content).setVisibility(View.VISIBLE);
        // content.findViewById(R.id.sel_title_layout).setVisibility(View.VISIBLE);
        // }else{
        // content.findViewById(R.id.sel_title_layout).setVisibility(View.VISIBLE);
        // }

        mixtopsel.setVisibility(View.VISIBLE);
        carrierView.findViewById(R.id.save_layout).setVisibility(View.VISIBLE);

    }

    /**
     * 设置删除选框选中
     */
    private void setDeleteCheck(boolean flag) {
        String f = "0";
        if (flag) {
            f = "1";
        }
        for (Map<String, String> map : olddatas) {
            map.put("checkFlag", f);
        }
    }

    /**
     * 添加按钮
     */
    private void initADD(TextView addTextview, String filter, final String zwbh, final KeyValueBean kvb,
                         final MyActorPopWindow.OnSelectListener listener) {
        if (kvlist.size() == 0) {
            kvlist = dBManagerUtil.getZWDatas("DIC_ZW", new KeyValueBean("PID", "VALUE", "CLASSIFICATION"), filter,
                    xmlPath + "DEMAND.db");
        }

        addTextview.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MyActorPopWindow pw = new MyActorPopWindow(MyDemandActivity.this, v, kvb, zwbh, listener, mjkey,
                        mj_total);
                pw.show(kvlist, olddatas, Constants.SortBeanTypeByField, true);
            }
        });
    }

    /**
     * 添加单选处理
     */
    private boolean singleSelect(String key, Map<String, String> select) {
        boolean flag = true;
        for (Map<String, String> map : olddatas) {
            if (select.get(key).equals(map.get(key))) {
                flag = false;
                break;
            }
        }

        if (flag) {
            olddatas.add(select);
        }

        return flag;
    }

    /**
     * 获取图斑类型列表
     */
    private List<KeyValueBean> getTblxList() {
        List<KeyValueBean> list = dBManagerUtil.getListDatas("DIC_TBLX", new KeyValueBean("PID", "VALUE"), null,
                xmlPath + "DEMAND.db");

        return list;
    }

    /**
     * 获取设施农业用地类型列表
     */
    private List<String> getSSLXList(String filter) {
        List<String> list = dBManagerUtil.getListDatas("DIC_ZW", "VALUE", filter, xmlPath + "DEMAND.db");

        return list;
    }

    /**
     * 获取最新的图斑类型
     */
    private KeyValueBean getTBLXFromList(List<Map<String, String>> list, String key) {
        KeyValueBean tblx = null;
        String val = list.get(list.size() - 1).get(key);
        for (KeyValueBean kv : tblxList) {
            if (val.equals(kv.getValue())) {
                tblx = kv;
                break;
            }
        }
        return tblx;
    }

    /**
     * 获取最新的设施农业用地类型
     */
    private String getSSLXFromList(List<Map<String, String>> list, String key) {
        String sslx = "种植业设施用地";
        if (list.size() > 0) {
            String val = list.get(list.size() - 1).get(key);
            for (String s : sslxList) {
                if (val.equals(s)) {
                    sslx = s;
                    break;
                }
            }
        }
        return sslx;
    }

    // -----------面积刷新------------
    public TextView tb_all_label;
    public TextView tb_all;
    public TextView tb_ok_label;
    public TextView tb_ok;
    public TextView tb_no_label;
    public TextView tb_no;
    public TextView tb_over_label;
    public TextView tb_over;

    public static final String pfmKey = "MJPFM";

    /**
     * 获取地块总面积
     */
    private String getTotal() {
        String mj = "0";
        if (oldUnit == 1) {
            mj = CommenUtil.formatterMJ(mj_total);
        } else if (oldUnit == 2) {
            mj = CommenUtil.MUtoPFM(String.valueOf(mj_total));
        }
        return mj;
    }

    @Override
    public void setSelectSave(boolean isSelectSave) {

    }

    /**
     * 刷新填报面积
     */
    public void refreshTBMJ(String key) {
        if (oldUnit == 1) {
            tb_all_label.setText("图斑面积(亩)");
            tb_ok_label.setText("已填报(亩)");
            tb_no_label.setText("未填报(亩)");
            tb_over_label.setText("已超出(亩)");
        } else if (oldUnit == 2) {
            tb_all_label.setText("图斑面积(平方米)");
            tb_ok_label.setText("已填报(平方米)");
            tb_no_label.setText("未填报(平方米)");
            tb_over_label.setText("已超出(平方米)");

            key = pfmKey;
        }
        tb_all.setText(getTotal());
        double tbmj = getTBMJ(key);
        tb_ok.setText(String.valueOf(tbmj));
        mj_dv = getmjDvalue(tbmj);
        if (mj_dv > 0 || mj_dv == 0) {
            tb_no_label.setVisibility(View.VISIBLE);
            tb_no.setVisibility(View.VISIBLE);
            tb_no.setText(String.valueOf(mj_dv));

            tb_over_label.setVisibility(View.GONE);
            tb_over.setVisibility(View.GONE);
        } else {
            double dv = Math.abs(mj_dv);

            tb_over_label.setVisibility(View.VISIBLE);
            tb_over.setVisibility(View.VISIBLE);
            tb_over.setText(String.valueOf(dv));

            tb_no_label.setVisibility(View.GONE);
            tb_no.setVisibility(View.GONE);
        }
    }

    /**
     * 获取已经填报的面积
     */
    private double getTBMJ(String key) {
        double to = 0;
        for (Map<String, String> map : olddatas) {
            String mj = map.get(key);
            if (StringUtil.isNotEmpty(mj)) {
                to += Double.valueOf(mj);
            }
        }

        to = Double.valueOf(CommenUtil.formatterMJ(to));
        return to;
    }

    /**
     * 获取面积差值
     */
    private double getmjDvalue(double tbmj) {
        double d = 0;
        if (oldUnit == 1) {
            d = mj_total;
        } else if (oldUnit == 2) {
            d = mj_total * 666.7;
        }
        d = d - tbmj;

        d = Double.valueOf(CommenUtil.formatterMJ(d));
        return d;
    }


    // -----------面积刷新【完】------------

    // +++++++++++++++++++++基本信息++++++++++++++++++++++++++++++++++++++
    /**
     * 总面积
     */
    public double mj_total = 0;
    /**
     * 面积差
     */
    public double mj_dv = 0;
    /**
     * 双击时间间隔
     */
    private long clickTime;
    LinearLayout maplayout;
    RelativeLayout.LayoutParams rl_h;
    RelativeLayout.LayoutParams rl_w;

    /**
     * 初始化基本信息页
     */
    private void initBaseInfo(File file) {
        // 设置地图高度
        rl_h = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                (Constants.screenHight * 2) / 5);
        rl_h.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        rl_w = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl_w.addRule(RelativeLayout.ALIGN_PARENT_TOP);

        maplayout = (LinearLayout) main.findViewById(R.id.map_layout);
        maplayout.setLayoutParams(rl_w);

        // **设置自然地块图片
        zrdkImageView = (ImageView) main.findViewById(R.id.zrdk_image);
        zrdkImageView.setImageBitmap(Constants.ZRDKBITMAP);
        zrdkImageView.setVisibility(View.GONE);

        LinearLayout infoLayout = (LinearLayout) main.findViewById(R.id.info_layout);
        infoLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // if ((System.currentTimeMillis() - clickTime) > 1000) {
                // clickTime = System.currentTimeMillis();
                // }else{
                if (zrdkImageView.getVisibility() == View.VISIBLE) {
                    maplayout.setLayoutParams(rl_w);
                    zrdkImageView.setVisibility(View.GONE);
                } else {
                    maplayout.setLayoutParams(rl_h);
                    zrdkImageView.setVisibility(View.VISIBLE);
                }
                // clickTime = 0;
                // }
            }
        });

        // **获取基本信息
        TextView baseInfo = (TextView) main.findViewById(R.id.info);

        // 解析thc配置文件
        InputStream input = CommenUtil.initStreamData(file.getProperties(), xmlPath, this);
        List<BasicProperties> fieldList = ThcParse.getXmlThc(input);

        // 根据字段从数据库中获取数据
        List<String> labels = new ArrayList<String>();
        List<String> fields = new ArrayList<String>();
        for (BasicProperties fd : fieldList) {
            if (fd.isShow()) {
                labels.add(fd.getLabel());
                fields.add(fd.getName());
            }
        }
        String tablename = CommenUtil.getTableName(file.getTable(), periodLabel);
        DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
        Map<String, String> data = DBImportUtil.getData(tablename, fields, "rowid", Constants.select.get("rowid"));

        // 处理数据
        String str = "";
        for (int i = 0; i < labels.size(); i++) {
            String val = data.get(fields.get(i));
            // added by 李忠义， “分割后自然地块编号”标签不显示
            if (labels.get(i).trim().equalsIgnoreCase("分割后自然地块编号")) {
                continue;
            }
            if (labels.get(i).endsWith("(亩)")) {
                Double area = 0.0;
                if (StringUtil.isNotEmpty(val)) {
                    area = Double.parseDouble(val);
                }
                /*if (area >= 99) {*/
                area = (Double) (area / 666.7);
                /*}*/

                val = CommenUtil.formatterMJ(area);
                mj_total = Double.valueOf(CommenUtil.formatterMJ(area));
            }
            if (i != labels.size() - 1) {
                if (((i + 1) % 2) == 0) {
                    str += labels.get(i) + "：" + val + " \n";
                } else {
                    str += labels.get(i) + "：" + val + "      ";
                }
            } else {
                str += labels.get(i) + "：" + val;
            }
        }
        baseInfo.setVisibility(View.VISIBLE);
        baseInfo.setText(str);
    }

    /**
     * 跳转至表单页面
     */
    private void goToAddForm(String rowid, File file) {
        Intent intent = new Intent(this, MyAddFormActivity.class);

        intent.putExtra("DKID", DKID);
        intent.putExtra("rowid", rowid);
        intent.putExtra("pkgPath", pkgPath);
        intent.putExtra("file", file);
        intent.putExtra("f3", f3);

        if (file.getAdd() != null) {
            intent.putExtra("bp", file.getAdd());
        }

        startActivity(intent);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);// 动画效果
    }

    // +++++++++++++++++++++ADD++++++++++++++++++++++++++++++++++++++

    /**
     * 新增表单面板
     *
     * @param add
     * @param carrierView
     * @param carrier_layout
     * @param file
     */
    private void initAddData(BasicProperties add, View carrierView, LinearLayout carrier_layout, final File file) {
        if (Constants.SELF.equals(add.getType())) {// 在本页
            // 显示保存按钮
            LinearLayout save_layout = (LinearLayout) carrierView.findViewById(R.id.save_layout);
            save_layout.setVisibility(View.VISIBLE);
            // 保存按钮
            save_layout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String table = CommenUtil.getTableName(file.getTable(), periodLabel);
                    int i = saveData(file, table, DKID);
                    switch (i) {
                        case 0:
                            return;
                        case 1:
                            CommenUtil.toast("保存成功！", MyDemandActivity.this);
                            break;
                        case 2:
                            CommenUtil.toast("保存失败！", MyDemandActivity.this);
                            break;

                        default:
                            break;
                    }
                }
            });
            initFormView(file, add, carrierView, carrier_layout, file.getFeild(), DKID);

        } else if (Constants.NEW.equals(add.getType())) {// 在新的页面
            // 显示添加按钮
            LinearLayout opreate_layout = (LinearLayout) carrierView.findViewById(R.id.opreate_layout);
            opreate_layout.setVisibility(View.VISIBLE);
            ImageView opreate_img = (ImageView) carrierView.findViewById(R.id.opreate_img);
            opreate_img.setImageResource(R.mipmap.add);

            opreate_layout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    goToAddForm(null, file);
                }
            });

        } else if (Constants.SELECT.equals(add.getType())) {// 列表数据添加
            // 显示保存按钮
            LinearLayout save_layout = (LinearLayout) carrierView.findViewById(R.id.save_layout);
            save_layout.setVisibility(View.VISIBLE);
            View addListView = initSelectList(carrier_layout);
            // initSelectData(file,add, addListView,save_layout);
        }
    }

    /**
     * 选择添加列表 是否要保存
     */
    public boolean selectSave = false;

    /**
     * 初始化选择添加列表视图
     */
    private View initSelectList(LinearLayout carrier_layout) {
        // 渲染
        // LinearLayout addListView = (LinearLayout)
        // LayoutInflater.from(this).inflate(R.layout.util_add_list, null);
        LinearLayout addListView = (LinearLayout) getLayoutInflater().inflate(R.layout.util_add_list, null);

        // 加入父组件
        carrier_layout.addView(addListView);

        return addListView;
    }

    /**
     * 刷新列表数据
     */
    private void refreshListView(AddListAdapter addListAdapter, ListView listview, List<Map<String, String>> olddatas,
                                 LinearLayout nodata) {
        addListAdapter.refresh(olddatas);
        if (olddatas.size() == 0) {
            listview.setVisibility(View.GONE);
            nodata.setVisibility(View.VISIBLE);
        } else {
            listview.setVisibility(View.VISIBLE);
            nodata.setVisibility(View.GONE);
        }

        refreshTBMJ("ZWMJ");
    }

    private List<KeyValueBean> kvlist = new ArrayList<KeyValueBean>();

    /**
     * 已经保存到数据库的表单数据
     */
    public Map<String, String> formDataMap = new HashMap<String, String>();
    /**
     * 表单修改后的数据
     */
    public Map<String, String> addMap = new HashMap<String, String>();
    /**
     * 表单修改后的数据--临时缓存
     */
    public Map<String, String> addTempMap = new HashMap<String, String>();

    public List<String> formkeys;
    public boolean isFormEdit = false;
    public boolean isClickSave = false;

    /**
     * 初始化本页新增表单
     */
    public void initFormView(final File file, BasicProperties addProp, View carrierView, LinearLayout carrier_layout,
                             String fkey, Object fvalue) {
        // 标题
        carrierView.findViewById(R.id.title_layout).setVisibility(View.VISIBLE);
        TextView title_textview = (TextView) carrierView.findViewById(R.id.title_textview);
        title_textview.setText(addProp.getTitle());

        // 解析thc文件
        InputStream inputStream = CommenUtil.initStreamData(file.getProperties(), xmlPath, this);
        List<BasicProperties> fieldList = ThcParse.getXmlThc(inputStream);
        formkeys = CommenUtil.basicPropertieToStrList(fieldList);

        formDataMap.clear();
        addMap.clear();

        // 获取旧数据
        String table = CommenUtil.getTableName(file.getTable(), periodLabel);

        String val = fvalue.toString();
        if (StringUtil.isNotEmpty(val) && !val.equals("0")) {
            List<Map<String, String>> datas = dBManagerUtil.getListData(table, formkeys, fkey, fvalue, dbPath);
            if (datas != null && datas.size() > 0) {
                formDataMap = datas.get(0);
                addMap = StringUtil.setMapToMap(formDataMap, addMap);
            } else {
                fvalue = null;
            }
        } else {
            formDataMap.clear();
        }

        FormUtil.fieldSet = "";
        boolean isClear = formDataMap.isEmpty();
        boolean isEnd = false;
        formDataMap.put(file.getFeild(), DKID);
        addMap.put(file.getFeild(), DKID);
        // 渲染
        for (BasicProperties field : fieldList) {
            // 继承
            if (StringUtil.isNotEmpty(field.getInherit())) {
                if (field.getInherit().equals("1")) { // 直接继承
                    String pfield = field.getPfeild();
                    if (Constants.select != null && !Constants.select.isEmpty()) {
                        if (addMap.get(field.getName()) == null || addMap.get(field.getName()).isEmpty()) {
                            String value = Constants.select.get(pfield);

                            // 处理亩和平方米的互换
                            if (field.getLabel().endsWith("（亩）")) {
                                Double area = Double.parseDouble(value);
                                if (area >= 99) {
                                    area = (Double) (area / 666.7);
                                }

                                DecimalFormat df = new DecimalFormat("######0.0000");
                                value = df.format(area) + "";
                            }

                            formDataMap.put(field.getName(), value);
                            addMap.put(field.getName(), value);
                        }
                    }
                } else if (field.getInherit().equals("-1")) {// -1，农户ID 自定义规则
                    // 【村编码+"-"+uuid】
                    if (Constants.select != null && !Constants.select.isEmpty()) {
                        String pfield = "CUNDM";
                        if (addMap.get(field.getName()) == null || addMap.get(field.getName()).isEmpty()) {
                            String value = Constants.select.get(pfield) + "-" + CommenUtil.createUUID();

                            formDataMap.put(field.getName(), value);
                            addMap.put(field.getName(), value);
                        }
                    }
                }
            } // 继承【完】

            if (fieldList.get(fieldList.size() - 1).getName().equals(field.getName())) {
                isEnd = true;// 如何检测过滤后的最后一个?
            }

            if (field.isShow()) {
                initAddLayout(field, isEnd, fieldList, carrier_layout);
            }

        } // for循环结束

        if (isClear) { // 渲染完成后，如果原来数据库里面没有表单数据，那么需要还原清空formDataMap
            addTempMap = StringUtil.setMapToMap(addMap, addTempMap);
            formDataMap.clear();
        }
    }

    /**
     * 保存表单数据
     */
    public int saveData(File file, String table, String dkid) {
        boolean isSuccess = false;
        isClickSave = true;

        // 判断是否有保存的数据
        if (addMap.isEmpty() || addMap.size() == 1) {
            CommenUtil.toast("数据不能全部为空", MyDemandActivity.this);
            return 0;
        } else { // 要保存
            // 判断是要更新数据 还是添加数据
            if (!formDataMap.isEmpty()) { // 更新
                // 判断是否有新的改动
                if (!formDataMap.equals(addMap)) {
                    String rowid = formDataMap.get("rowid");

                    addMap.remove("rowid");
                    // 判断是保存到一个表 还是 两个表
                    if (StringUtil.isNotEmpty(file.getLtable())) {
                        if (StringUtil.isNotEmpty(rowid)) {
                            InputStream inputStream = CommenUtil.initStreamData(file.getProperties(), xmlPath, this);
                            final List<BasicProperties> fieldList = ThcParse.getXmlThc(inputStream);
                            isSuccess = dBManagerUtil.updateTwoTable(table, file.getLtable(), addMap, fieldList, rowid,
                                    dbPath);
                        } else {
                            isSuccess = false;
                        }
                    } else {
                        isSuccess = dBManagerUtil.updateById(addMap, formkeys, table, file.getFeild(), DKID, dbPath);
                    }
                } else {
                    isSuccess = true;
                }
            } else {// 添加

                // 判断addMap是否为空
                if (!addMap.isEmpty()) {
                    addMap.put(file.getFeild(), dkid);// 不知道地块编号外键是否真的可以编辑
                    addMap.remove("rowid");// 让rowid自增

                    // 判断是保存到一个表 还是 两个表
                    if (StringUtil.isNotEmpty(file.getLtable())) {
                        InputStream inputStream = CommenUtil.initStreamData(file.getProperties(), xmlPath, this);
                        final List<BasicProperties> fieldList = ThcParse.getXmlThc(inputStream);
                        isSuccess = dBManagerUtil.addTwoTable(table, file.getLtable(), addMap, fieldList, dbPath);
                    } else {// 一个表
                        isSuccess = dBManagerUtil.add(addMap, formkeys, table, "", dbPath);
                    }

                } else {
                    isSuccess = true;
                }
            }
        }

        if (isSuccess) {
            formDataMap = StringUtil.setMapToMap(addMap, formDataMap);// 给oldDataMap赋值，防止出现多次添加的情况

            // 保存已编辑
            if (StringUtil.isNotEmpty(file.getLtable())) {// 列表
                if (f3) {
                    f3 = false;
                    changeComplete("f3", "1");
                }
            } else {// 单独表单
                if (f2) {
                    f2 = false;
                    changeComplete("f2", "1");
                }
            }

            //保存进度记录
            RecordDBManager rcdDB = new RecordDBManager(MyDemandActivity.this);
            rcdDB.add(DKID, YFBHU, "4", "003");

            return 1;
        } else {
            return 2;
        }

    }

    /**
     * 初始化表单的一个输入框【一个属性】
     */
    private void initAddLayout(BasicProperties field, boolean isEnd, List<BasicProperties> fieldList,
                               LinearLayout carrier_layout) {
        FormUtil formUtil = new FormUtil(this, field, isEnd, fieldList);

        // 输入规则
        String input = field.getInput();// 组合方式具体有哪些，不能太动态
        if (input.startsWith("0") || input.contains("|0") || input.startsWith("5") || input.contains("|5")
                || input.startsWith("3") || input.contains("|3") || input.startsWith("4") || input.contains("|4")
                || input.startsWith("6") || input.contains("|6")) {// 文本输入框
            if (input.startsWith("5") || input.contains("|5")) {// 选框
                // fieldset（50：单选；53：多选；）；abc（56：单选；57：多选）

                // 单选还是多选
                boolean isSingle = true;
                if (input.contains("53") || input.contains("57")) {// 多选
                    isSingle = false;
                }
                // 列表分组条件 以及 显示和保存的格式
                String beanType = Constants.SortBeanTypeByABC;
                if (input.contains("50") || input.contains("53")) {// 多选
                    beanType = Constants.SortBeanTypeByField;
                }
                int showType = 0;
                if (input.contains("501") || input.contains("531") || input.contains("561") || input.contains("571")) {
                    showType = 1;
                }
                if (input.contains("502") || input.contains("532") || input.contains("562") || input.contains("572")) {// 如：103
                    showType = 2;
                }
                if (input.contains("503") || input.contains("533") || input.contains("563") || input.contains("573")) {// 如：水稻
                    showType = 3;
                }

                List<KeyValueBean> list = getInputSelectDatas(field);
                View child = formUtil.initSelectInput(null, formDataMap, list, isSingle, beanType);
                carrier_layout.addView(child);
            } else {// 普通输入框

                if (!"002".equals(input)) {
                    View child = formUtil.initNormalEditText(formUtil.getTextType(input), -1, null, formDataMap);
                    carrier_layout.addView(child);
                } else {
                    View child = formUtil.initTextArea(null, formDataMap);
                    carrier_layout.addView(child);
                }
            }
        }

        // 拍照

        // 录音

    }

    /**
     * 获取表单 选择输入框的选择数据
     */
    private List<KeyValueBean> getInputSelectDatas(BasicProperties field) {
        List<String> fields = new ArrayList<String>();
        fields.add("PID");
        fields.add("VALUE");
        fields.add("CLASSIFICATION");

        List<KeyValueBean> list = new ArrayList<KeyValueBean>();
        List<Map<String, String>> datas = dBManagerUtil.getListData(field.getDictable(), fields, field.getFilter(),
                xmlPath + "DEMAND.db");

        for (Map<String, String> map : datas) {
            KeyValueBean kv = new KeyValueBean();
            kv.setKey(map.get("PID"));
            kv.setValue(map.get("VALUE"));
            kv.setFieldset(map.get("CLASSIFICATION"));
            list.add(kv);
        }
        return list;
    }

    // +++++++++++++++++++++MENU ITEM 列表++++++++++++++++++++++++++++++++++++++

    /**
     * 初始化列表视图
     *
     * @param carrier_layout
     */
    public View initListView(LinearLayout carrier_layout) {
        View childView = (View) getLayoutInflater().inflate(R.layout.util_listview, null);
        childView.findViewById(R.id.title_layout).setVisibility(View.VISIBLE);
        carrier_layout.addView(childView);
        return childView;
    }

    /**
     * 初始化列表，保存上次数据
     *
     * @param file
     * @param carrier_layout
     */
    public void initListData(final File file, View childView) {
        final ListView listView = (ListView) childView.findViewById(R.id.list);
        TextView title_text = (TextView) childView.findViewById(R.id.title_textview);
        // 设置标题
        String name = file.getName();
        if (!name.endsWith("列表")) {
            name = name + "列表";
        }
        title_text.setText(name);

        // 获取列表数据
        List<Item> itemList = file.getItem();
        List<String> keys = CommenUtil.itemToStrList(itemList);
        String table = CommenUtil.getTableName(file.getTable(), periodLabel);
        final List<Map<String, String>> listDatas = dBManagerUtil.getListData(table, keys, file.getFeild(), DKID,
                dbPath);

        final SlideAdapter slideAdapter = new SlideAdapter(this, listDatas, 0, itemList, null, title_text, name);
        listView.setAdapter(slideAdapter);
        slideAdapter.setClicklistener(new SlideAdapter.ClickListenerInterface() {

            @Override
            public void doOperate(int position) { // 点击删除
                isAlertDown(MyDemandActivity.this, "确定要删除该记录吗？", "删除", "取消", isListViewDelete, null, slideAdapter,
                        listView, position, file);
            }

            @Override
            public void doItem(int position) {// 点击查看详情
                String rowid = listDatas.get(position).get("rowid");
                goToAddForm(rowid, file);
            }
        });
        listView.setDivider(null);
        slideAdapter.notifyDataSetChanged();
    }

    // -------------------------------------------------------------
    public static final int isCancle = -1;
    public static final int isSeletListDelete = -2;
    public static final int isListViewDelete = -3;

    /**
     * 弹出确认框【前5个参数 为 必填】
     *
     * @param activity
     * @param str            提示语句
     * @param right          右边 确认按钮文字
     * @param left           左边 取消按钮文字
     * @param type           类型
     * @param addListAdapter 选择列表adapter
     * @param slideAdapter   列表adapter
     * @param listview
     * @param position
     * @param file
     */
    public void isAlertDown(final Activity activity, String str, String right, String left, final int type,
                            final AddListAdapter addListAdapter, final SlideAdapter slideAdapter, final ListView listview,
                            final int position, final File file) {

        final AlertDialog alertDialog = new AlertDialog(activity, str, right, left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {

            @Override
            public void doConfirm() {
                alertDialog.dismiss();

                switch (type) {
                    case isCancle: // 撤销
                        // 数据撤销

                        // 退出
                        activity.finish();
                        activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
                        break;
                    case isSeletListDelete: // 选择列表删除
                        olddatas.remove(position);
                        refreshListView(addListAdapter, listview, olddatas, nodata);
                        CommenUtil.toast("删除成功！", MyDemandActivity.this);
                        selectSave = true;
                        break;
                    case isListViewDelete: // 列表删除
                        String rowid = slideAdapter.mapList.get(position).get("rowid");
                        String table = CommenUtil.getTableName(file.getTable(), periodLabel);
                        boolean flag = false;
                        // 判断是保存到一个表 还是 两个表
                        if (StringUtil.isNotEmpty(file.getLtable())) {
                            flag = dBManagerUtil.deleteTwoTable(table, file.getLtable(), "rowid", rowid, dbPath);

                        } else {// 一个表
                            flag = dBManagerUtil.deleteById(table, "rowid", rowid, dbPath);
                        }
                        if (flag) {
                            slideAdapter.remove(position);

                            CommenUtil.toast("删除成功！", MyDemandActivity.this);
                        } else {
                            CommenUtil.toast("删除失败！", MyDemandActivity.this);
                        }
                        break;

                    default:

                        break;
                }
            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
            }
        });
    }

    /**
     * 退出
     */
    private void goBack() {
        // Constants.oldTBLX = oldTBLX;

        if (selectSave || (!isClickSave && !addMap.isEmpty() && !formDataMap.equals(addMap))) {
            isAlertDown(this, "当前地块填报未完成，是否真的要离开？", "离开", "继续填报", isCancle, null, null, null, -1, null);
        } else {
            Constants.data_refresh = true;
            finish();
            overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
        }
    }

    public boolean f1 = true, f2 = true, f3 = true;

    /**
     * 判断是否调查完成
     */
    private void changeComplete(String fkey, String fvalue) {

        String dkid = taskName + CommenUtil.getDCQ(periodLabel)
                + Constants.select.get("DKBHU");
        DKSearchDBManager db = new DKSearchDBManager(this);
        boolean f = db.changeStatus(2, dkid, fkey, fvalue);
        if (f) {
            String table = CommenUtil.getTableName("样方自然地块", periodLabel);
            dBManagerUtil.changeComplete(table, Constants.select.get("DKBHU"), dbPath);
        }
    }

    @Override
    protected void onDestroy() {
        new MSApplication().deleteActivity(this);
        super.onDestroy();
    }

    OnClickListener backListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            goBack();
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
        }
        return true;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case 601:
                double areaValue = data.getExtras().getDouble("areaValue");
                if (oldUnit == 1) {
                    mj_input.setText(CommenUtil.formatterMJ(areaValue));
                } else {
                    mj_input.setText(CommenUtil.MUtoPFM(String.valueOf(areaValue)));
                }
                break;
            case 602:
                break;
        }
    }

}
